package com.ruizhong.integratedmediawithoutc.controller;



import com.ruizhong.integratedmediawithoutc.entity.TMaterial;
import com.ruizhong.integratedmediawithoutc.server.WebSocketServer;
import com.ruizhong.integratedmediawithoutc.service.TMaterialService;
import com.ruizhong.integratedmediawithoutc.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/material/api")
@CrossOrigin
public class MaterialController {

    @Autowired
    private TMaterialService tMaterialService;

    @GetMapping("/getMaterialList/{userName}")
    public Result getMaterialList(@PathVariable(value = "userName") String userName ){
        List<HashMap<String, String>> materialList = tMaterialService.getMaterialList();
        HashMap<String, Object> resMap = new HashMap<>();
        resMap.put("data",materialList);
        return new Result(ResultCode.success,null,resMap);
    }

    @GetMapping("/getResourceList/{userName}/{programType}")
    public Result getResourceList(@PathVariable(value = "userName") String userName,@PathVariable(value = "programType",required = false) String programType){
        List<TMaterial> resourceList = tMaterialService.getResourceList(programType);
        HashMap<String, Object> resMap = new HashMap<>();
        resMap.put("data",resourceList);
        return new Result(ResultCode.success,null,resMap);
    }

@DeleteMapping("/deleteAllResources")
public Result deleteAllResources(){
        tMaterialService.deleteAllResources();
        return new Result(ResultCode.success,"删除成功",null);
}

    @PostMapping("/addResources")
    public Result addResources(@RequestBody Map<String,Object> conditionMap) throws IOException {
        ArrayList<Map<String, Object>> data = (ArrayList<Map<String, Object>>) conditionMap.get("data");
        for (Map<String, Object> videoInfo : data) {
            videoInfo.put("filename",videoInfo.get("file"));
        }
        tMaterialService.addResources(conditionMap);


//        TCPUtil.sendWithReplies(conditionMap,wsToken);
        return new Result(ResultCode.success,null,null);
    }

    @PostMapping("/deleteResource")
    public Result deleteResource(@RequestBody Map<String,Object> conditionMap){
//        Map<String, Object> resMap = TCPUtil.send(conditionMap);
        tMaterialService.deleteResource(conditionMap);
        return new Result(ResultCode.success,"null",null);
    }

    @PostMapping("/onDemand")
    public Result onDemand(@RequestBody Map<String,Object> conditionMap) throws IOException {
        Map<String, Object> resMap = TCPUtil.send(conditionMap);
        return new Result(ResultCode.success,null,resMap);
    }

    @PostMapping("/onDemandWithTrans")
    public Result onDemandWithTrans(@RequestBody Map<String,Object> conditionMap) throws IOException {
        String tokenId = conditionMap.get("tokenId").toString();
        Map<String, Object> previewMap = WebSocketServer.preViewMap.get(tokenId);
        Integer playMode = (Integer) previewMap.get("playMode");
        if (playMode != null) {
            HashMap<String, Object> removeMap = new HashMap<>();
            removeMap.put("user_name", previewMap.get("user_name"));
            ArrayList<Map<String, Object>> dataList = new ArrayList<>();
            HashMap<String, Object> dataMap = new HashMap<>();
            String srsServer = "http://"+ SRSUtil.srsServer_ip+":1985";
            String streamUrl = null;
            switch (playMode) {
                case 0:
                    removeMap.put("command", 15);
                    dataMap.put("pl_id", previewMap.get("pl_id"));
                    streamUrl = previewMap.get("suffix")+"_p_"+previewMap.get("pl_id")+".flv";
                    break;
                case 1:
                    //                    关闭资源点播
                    removeMap.put("command", 13);
                    dataMap.put("suffix", previewMap.get("suffix"));
                    streamUrl = previewMap.get("suffix")+"_m_"+previewMap.get("file_id")+".flv";
                    break;

            }
            dataList.add(dataMap);
            removeMap.put("data", dataList);

//            srs踢流
            Map<String, Object> streamsMap = SRSUtil.getStreams();
            ArrayList<Map<String, Object>> streams = (ArrayList<Map<String, Object>>) streamsMap.get("streams");
            String cid = null;
            for (Map<String, Object> stream : streams) {
                if (streamUrl.contains(stream.get("name").toString())){
                    cid = ((Map<String,Object>)stream.get("publish")).get("cid").toString();
                }
            }
            if (playMode == 1){
                SRSUtil.kickStream(srsServer,cid);
                TCPUtil.send(removeMap);
            }
        }
        Map<String, Object> resMap = TCPUtil.send(conditionMap);
        Map<String, Object> data = (Map<String, Object>) resMap.get("data");
        final String url = data.get("url").toString().replace("\n","");
        ArrayList<Map<String, Object>> sourceData = (ArrayList<Map<String, Object>>) conditionMap.get("data");
        String file_id = sourceData.get(0).get("file_id").toString();
        String[] urlArr = url.split("/");
        final String transUrl = "rtmp://"+SRSUtil.srsServer_ip+":1935/live/"+urlArr[urlArr.length-1]+"_m_"+file_id;
        String flvUrl = "http://"+SRSUtil.srsServer_ip+":8080/live/"+urlArr[urlArr.length-1]+"_m_"+file_id+".flv";
        data.put("flvUrl",flvUrl);
        new Thread(new Runnable() {
            @Override
            public void run() {
                   RtspToRtmpStreamer.transToFlvWithProcessBuilder(url,transUrl);
            }
        }).start();

        return new Result(ResultCode.success,null,resMap);
    }


    @PostMapping("/stopOnDemand")
    public Result stopOnDemand(@RequestBody Map<String,Object> conditionMap){
        System.out.println(conditionMap);
        Map<String, Object> resMap = TCPUtil.send(conditionMap);
        System.out.println(resMap);
        return new Result(ResultCode.success,null,resMap);
    }

}
